<template>
    <el-dialog v-model="formVisible" title="修改计划" width="40%" @close="resetFormVisible">
        <!-- 对话主体区域 -->
        <el-form ref="formRef" :model="form" :rules="formRules" label-width="110px">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="修改开始时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  clearable
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                  v-model="form.endTime"
                  type="datetime"
                  placeholder="修改结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  clearable
              />
<!--              format="YYYY/MM/DD hh:mm:ss"加value-->
            </el-form-item>
          <el-form-item label="" prop="maintenanceNo">
            <el-select
                v-model="form.maintenanceNo"
                clearable
                placeholder="维护项编号"
                @change="handleSelectChange"
                style="width: 240px"
            >
              <el-option
                  v-for="item in selectOptions"
                  :key="item.maintenanceNo"
                  :label="item.maintenanceNo"
                  :value="item.maintenanceNo"
              />
            </el-select>
          </el-form-item>
            <el-form-item label="维护项目" prop="mainteItem">
              <el-input v-model="form.mainteItem" readonly/>
            </el-form-item>
            <el-form-item label="维护要领" prop="mainteEssentials">
              <el-input
                  v-model="form.mainteEssentials"
                  autosize
                  type="textarea"
                  readonly/>
            </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="doUpd">修改</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script setup>
import { watch, ref } from 'vue'
import { ElMessage } from 'element-plus';
import mpApi from '@/api/maintenancePlan'

const props = defineProps({
  visible: Boolean,
  id: Number
})

const emit = defineEmits(['closeDialog2f', 'freshMaintainPlans2f'])
const formVisible = ref(false);

// 子组件监听父组件prop
watch(props, (nweProps, oldPorps) => {
    formVisible.value = nweProps.visible;
    form.value.dataSeq = nweProps.id;
    getUpdPlanDetail(nweProps.id);
    if (formVisible.value) {
      getMaintenanceDefinitionData();
    }
})

// 对话表单
const form = ref({
  dataSeq: '',
  maintenanceNo: '',
  startTime: '',
  endTime: '',
  mainteItem: '',
  mainteEssentials: '',
})

// 根据计划序号查询，并显示应用详情
const getUpdPlanDetail = async (id) => {
    const res = await mpApi.getSingleMaintenancePlanData({ dataSeq: id })
    if (res.data.status) {
      // 查出应用详情并填充,过后尝试 form.value=res.data.data 可不可行
      form.value.maintenanceNo = res.data.data.maintenanceNo;
      form.value.startTime = res.data.data.startTime;
      form.value.endTime = res.data.data.endTime;
      form.value.mainteItem = res.data.data.mainteItem;
      form.value.mainteEssentials = res.data.data.mainteEssentials;
    } else {
        ElMessage.error("获取计划失败")
    }
}

const resetFormVisible = () => {
    formVisible.value = false;
    // 本来要调用ref的resetFields()
    form.value.dataSeq = '';form.value.maintenanceNo = '';form.value.startTime = '';
    form.value.endTime = ''; form.value.mainteItem = '';form.value.mainteEssentials = '';
    emit("closeDialog2f", formVisible.value);
};

// 取消修改（多加一层以备需求）
const closeDialog = () => {
    resetFormVisible();
}

const formRef = ref(null);

const doUpd = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            const res = await mpApi.updMaintenancePlanData(form.value);
            if (res.data.status) {
                ElMessage.success("修改计划成功")
                //通知父组件刷新
                emit("freshApps2f", true);
            } else {
                ElMessage.error("修改失败")
            }
            //重置表单，关闭对话
            resetFormVisible();
        } else {
            ElMessage.error('数据格式错误！')
        }
    })
}

const selectOptions = ref([]);
// 获取维修项
const getMaintenanceDefinitionData = async () => {
  const res = await mpApi.getMaintenanceDefinitionData();
  if (res.data.status) {
    //用all前缀来接收保存
    selectOptions.value = res.data.data;
  } else {
    ElMessage.error("获取后端数据失败");
    console.log(res.data.message);
  }
}
// 监听下拉框选择变化
const handleSelectChange = (selectedValue) => {
  const selectedItem = selectOptions.value.find(
      item => item.maintenanceNo === selectedValue
  );
  const maintenanceDefinition = selectedItem;
  form.value.mainteItem = maintenanceDefinition.mainteItem;
  form.value.mainteEssentials = maintenanceDefinition.mainteEssentials;
};
</script>
  